package com.qiche.controller.mgr;

import com.qiche.aspect.Result;
import com.qiche.config.YmlConfig;
import com.qiche.enums.ResultEnum;
import com.qiche.model.Evaluation;
import com.qiche.model.SpecialOffer;
import com.qiche.model.User;
import com.qiche.service.EvaluationService;
import com.qiche.service.SpecialOfferService;
import com.qiche.util.FastDFSUtils;
import com.qiche.util.UserUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 特价控制器
 */
@RestController
@RequestMapping("/specialOffer")
public class SpecialOfferController {
    @Autowired
    private SpecialOfferService specialOfferService;
    @Autowired
    private YmlConfig ymlConfig;

    /**
     * 设置特价
     * @param specialOffer
     * @return
     */
    @PostMapping("/set")
    public Result setSpecialOffer(@RequestBody SpecialOffer specialOffer) {
        User currentUser= UserUtils.getCurrentUser();
        SpecialOffer specialOfferInDb=specialOfferService.selectByMerchantId(currentUser.getMerchantId());
        int changeCount=0;
        if(specialOfferInDb==null){
            specialOffer.setMerchantId(currentUser.getMerchantId().longValue());
            changeCount= specialOfferService.save(specialOffer);
        }else{
            specialOfferInDb.setDescription(specialOffer.getDescription());
            specialOfferInDb.setPosterImg(specialOffer.getPosterImg());
            changeCount= specialOfferService.updateNotNull(specialOfferInDb);
        }
        if(changeCount>0){
            return Result.createBySuccessMessage("保存成功");
        }
        return Result.createByErrorMessage("保存失败");
    }

    @ApiOperation(value = "上传特价图片")
    @PostMapping("/upload")
    public Result uploadImg(MultipartFile file) {
        try {
            String paths = FastDFSUtils.uploadPic(file);
            return Result.createByResultEnum(ResultEnum.SUCCESS, ymlConfig.getFastdfsDomainUrl() + paths);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.createByResultEnum(ResultEnum.FAILURE);
        }
    }

    @ApiOperation(value = "当前门店获取当前特价信息")
    @GetMapping("/get")
    public Result getSpecialOffer() {
        User currentUser= UserUtils.getCurrentUser();
        SpecialOffer specialOffer=specialOfferService.selectByMerchantId(currentUser.getMerchantId());
        return Result.createBySuccess(specialOffer);
    }
}
